<template>

    <div class="pricing-table">
        <table :class="{ 'pricing-simply': shop.ss_currency != 'USD', 'pricing-table-branding': brandingPrice }">
            <thead>
                <tr>
                    <th class="table-size"><span>Size</span></th>
                    <th class="table-color"><span>Color</span></th>

                    <th class="table-product">
                        <span v-text="brandingPrice ? 'Product' : 'Cost'"></span>
                        <UxToolTip v-if="!brandingPrice" content="Shipping and taxes excluded." placement="top" />
                        <CommonLevelDiscount :level="setting" type="icon" />
                    </th>
                    <th class="table-brand">
                        <span>Branding</span>
                        <UxToolTip content="Branding charges include costs of<br />packaging bags and hang tags"
                                   placement="top" />
                        <CommonLevelDiscount :level="setting" type="icon" />
                    </th>
                    <th class="table-cost">
                        <span>Cost</span>
                        <UxToolTip content="Shipping and taxes excluded." placement="top" />
                    </th>

                    <th class="table-retail">
                        <span>Retail price</span>
                        <UxToolTip content="Note that when you add a product to your store, we will only sync the product's price that you've set on our site without changing the currency. To avoid any price discrepancies, please ensure that the product price is set in your store's currency."
                                   placement="top" />
                        <SynchronizePriceInput v-model="retail" :fixed="0.01" :precision="2" :unit="unit"
                                               @change="changePriceByTitle('retail')" />
                    </th>

                    <th class="table-profit">
                        <span>Profit</span>
                        <SynchronizePriceInput v-model="profit" :fixed="0.01" :precision="2" :unit="unit"
                                               @change="changePriceByTitle('profit')" />
                    </th>
                    <th class="table-margin">
                        <span>Profit margin</span>
                        <SynchronizePriceInput v-model="point" :precision="2" unit="%"
                                               @change="changePriceByTitle('point')" />
                    </th>
                </tr>
            </thead>
            <tbody>

                <tr v-for="row in table" :key="row.sku + row.size_id" :size-id="row.size_id"
                    :class="{ 'pricing-size': row.count > 0, 'pricing-child': !row.count }"
                    @click="setRowHidden($event, row)">
                    <td class="table-size">
                        <template v-if="row.count > 0">
                            <i class="iconfont icon-xia"></i>
                            <span v-text="row.size_name"></span>
                        </template>
                    </td>
                    <td class="table-color">
                        <span v-if="row.count > 0" v-text="row.count + ' Colors'"></span>
                        <span v-else>
                            <i :style="{ backgroundColor: row.color_num }"></i>
                            <em v-text="row.color_name"></em>
                        </span>
                    </td>
                    <td class="table-product">
                        <CommonLevelDiscount :level="setting" :price="row.original" :blank="product.is_blank"
                                             type="unit|discount" />
                    </td>
                    <td class="table-brand">
                        <!-- <CommonCurrencyRate :price="brandingPrice" :cover="setting" type="unit|price" /> -->
                        <CommonLevelDiscount :level="setting" :price="brandingPrice" type="unit|discount" />
                    </td>
                    <td class="table-cost" v-text="setting.currency + ' ' + getPriceFixed(row.cost)"></td>

                    <td class="table-retail">
                        <SynchronizePriceInput v-model="row.retail" :fixed="0.01" fill="0" :precision="2" :unit="unit"
                                               @change="changePriceByRow(row, 'retail')" />
                    </td>
                    <td class="table-profit">
                        <SynchronizePriceInput v-model="row.profit" :fixed="0.01" fill="0" :precision="2" :unit="unit"
                                               @change="changePriceByRow(row, 'profit')" />
                    </td>
                    <td class="table-margin">
                        <SynchronizePriceInput v-model="row.point" fill="0" :precision="2" unit="%"
                                               @change="changePriceByRow(row, 'point')" />
                    </td>
                </tr>
            </tbody>
        </table>

        <div class="pricing-notify" v-if="setting.price_notify == 'notify'">
            <cite>
                <img src="@/assets/images/synchronize/synchronize-exceed.png" alt="">
                <p>When you last added products to your store, you selected a different currency. Would you like to
                    convert the
                    product prices to the current currency using the current exchange rate?</p>
                <button @click="setCurrency()">Yes</button>
                <button @click="setting.price_notify = 'nochange'">No</button>
            </cite>

        </div>
    </div>

</template>
<script>
import { mapGetters, mapState } from "vuex";
export default {
    name: "SynchronizePricingVanriants",
    props: {
        product: { type: Object, required: true },
    },
    data () {
        return {
            retail: '',
            profit: '',
            point: '',
            table: [],
            variants_map: null,

        };
    },
    computed: {
        ...mapState("synchronize", {
            clothes: "clothes",
            setting: "setting",
            shop: "shop",
        }),

        unit () {
            if (this.shop.ss_currency != 'USD') {
                return this.shop.ss_currency
            } else {
                return this.setting.currency || 'USD';
            }
        },


        brandingPrice () {
            const tag = this.setting.tag_design_info;
            const pack = this.setting.pack_design_info;
            const tagPrice = tag ? tag.total_price : 0
            const packPrice = pack ? pack.total_price : 0
            return tagPrice + packPrice;
        },

    },
    watch: {
        'product.variants' () { this.getTable() },
    },
    methods: {

        mathMound (value, n) {
            n = n === undefined ? 1 : n;
            let bei = Math.pow(10, n);
            let res = Math.round(value * bei) / bei;
            return +parseFloat(res.toPrecision(12));
        },

        // 获取表格
        getTable () {
            const variants = this.product.variants || [];
            const table = [];
            const size_map = new Map();
            const select_color = this.product.select_color || [];
            const select_sizes = this.product.select_sizes || [];
            const variants_map = new Map();
            const lines = [];

            // 过滤掉未选中的和库存不足的
            variants.map((item) => {
                if (item.quality <= -999) {
                    // 库存不足，或是本身就禁用了
                } else if (select_color.indexOf(item.color_id) < 0) {
                    // 没有选中颜色
                } else if (select_sizes.indexOf(item.size_id) < 0) {
                    // 没有选中尺码
                } else {
                    const cache = size_map.get(item.size_id);

                    if (cache) {
                        cache.push(item);
                    } else {
                        size_map.set(item.size_id, [item])
                    }

                    variants_map.set(item.sku, item);
                }
            });
            // 选中的尺码
            select_sizes.map(size_id => {
                const cache = size_map.get(size_id) || [];
                const first = cache[0];
                if (cache.length > 0) {
                    const row = {
                        sku: size_id,
                        count: cache.length, // 行
                        size_id: size_id,
                        size_name: first.size_name,
                        original: first.original, // 商品价格
                        cost: first.cost, // 原价,向上取整
                        retail: first.retail, // 零售价
                        profit: first.profit, // 利润
                        point: first.point, // 利润率
                    }
                    table.push(row);
                    lines.push(first);
                    cache.map(item => table.push(JSON.parse(JSON.stringify(item))))
                }
            });

            this.retail = '';
            this.profit = '';
            this.point = '';
            this.table = table;
            this.variants_map = variants_map;
            lines.map(line => this.changePriceBitch(line))
        },


        // 更新价格
        updateVariants (row) {
            const active = this.variants_map ? this.variants_map.get(row.sku) : null;
            if (active) {
                active.point = row.point;
                active.retail = row.retail;
                active.profit = row.profit;
            }

        },

        // 价格格式化
        getPriceFixed (price) {
            return (this.mathMound(price) * 0.01).toFixed(2)
        },

        // 改行的价格
        changePriceBitch (row, name) {
            const list = row.count > 0 ? this.table.filter(i => i.size_id == row.size_id) : [row];

            list.map(item => {

                // 利润率
                // let point = (parseFloat(item.point) || 0) / 100;
                // 成本价
                // let cost = 100 * parseFloat(item.cost) || 0;
                // 利润
                // let profit = 100 * parseFloat(item.profit) || 0;
                // 零售价
                // let retail = 100 * parseFloat(item.retail) || 0;

                if (name == "point") {
                    // 利润率
                    item.point = this.mathMound(Math.min(row.point, 99), 2); // 利润率不能大于99
                    item.retail = this.mathMound(item.cost * 100 / (100 - item.point), 0);
                    item.profit = this.mathMound(item.retail - item.cost, 0)

                } else if (name == "profit") {
                    // 利润
                    item.profit = this.mathMound(row.profit, 0);
                    item.retail = this.mathMound(item.cost + item.profit, 0)
                    item.point = this.mathMound(100 * item.profit / item.retail, 2)
                } else if (name == "retail") {
                    // 售价
                    item.retail = this.mathMound(row.retail, 0);
                    item.profit = this.mathMound(item.retail - item.cost, 0)
                    item.point = this.mathMound(100 * item.profit / item.retail, 2)
                }

                if (!item.count) {
                    // 奇怪要这么写
                    this.updateVariants(item);
                }
            })

            if (!row.count) {
                // 行内，要计算范围
                const title_row = [];
                const retail_list = [];
                const profit_list = [];
                const point_list = [];
                this.table.map(item => {
                    if (item.size_id != row.size_id) {
                        // 忽略
                    } else if (item.count > 0) {
                        title_row.push(item);
                    } else {
                        retail_list.push(item.retail)
                        profit_list.push(item.profit)
                        point_list.push(item.point)
                    }
                });

                title_row.map(item => {

                    const retail_min = Math.min(...retail_list);
                    const retail_max = Math.max(...retail_list);
                    const profit_min = Math.min(...profit_list);
                    const profit_max = Math.max(...profit_list);
                    const point_min = Math.min(...point_list);
                    const point_max = Math.max(...point_list);

                    if (retail_min == retail_max) {
                        item.retail = retail_min;
                    } else {
                        item.retail = retail_min + '-' + retail_max;
                    }

                    if (profit_min == profit_max) {
                        item.profit = profit_min;
                    } else {
                        item.profit = profit_min + '-' + profit_max;
                    }

                    if (point_min == point_max) {
                        item.point = point_min;
                    } else {
                        item.point = point_min + '-' + point_max;
                    }

                })
            }
        },

        // 修改行
        changePriceByRow (row, name) {
            this.changePriceBitch(row, name);
            this.retail = '';
            this.profit = '';
            this.point = '';
        },

        // 标题的修改价格
        changePriceByTitle (name) {
            const keys = ['retail', 'profit', 'point']
            keys.map(key => {
                if (key == name) {
                    const precision = key == 'point' ? 2 : 0;
                    const value = this.mathMound(this[key], precision)
                    this[key] = value;
                    this.point = Math.min(this.point, 99)
                    this.table.map(row => {
                        if (row.count > 0) {
                            row[key] = value;
                            this.changePriceBitch(row, key)
                        }
                    })
                } else {
                    this[key] = '';
                }
            })
        },

        // 显示或隐藏行
        setRowHidden (event, row) {

            if (event.target.closest(".pricing-number")) {
                // 点击input不用管
            } else if (row.count > 0) {

                const body = event.target.closest('tbody')
                const childs = body ? body.querySelectorAll('tr[size-id=' + row.sku + ']') : [];
                const parent = event.target.closest('tr');
                const open = parent ? parent.getAttribute('open') : false;

                Array.prototype.slice.call(childs).map(item => {
                    if (open) {
                        item.removeAttribute('open')
                    } else {
                        item.setAttribute('open', 'open')
                    }
                });
            }
        },

        // 设置货币
        setCurrency () {
            this.setting.price_notify = 'change';
            this.setting.currency = this.$store.state.currency;
            this.setting.rate = this.$store.state.rate;
            this.$store.commit("synchronize/SET_VARIANTS", this.clothes);
        }
    },
    created () {
        this.getTable();
    },
};
</script>
<style lang="scss" scoped>
.pricing-table {
    margin-top: 16px;
    position: relative;

    .pricing-number {
        flex-direction: row;
        margin: 0 auto;
        width: 132px;
        height: 28px;

        &::v-deep b {
            display: none;
        }

        &::v-deep input {
            vertical-align: top;
            height: 28px;
            box-sizing: border-box;
            text-align: center;
            padding-left: 36px;
            padding-right: 6px;

            &:focus {
                outline: none;
            }

            &:hover {
                outline: none;
            }
        }

        &::v-deep em {
            line-height: 26px;
            height: 26px;
            position: absolute;
            left: 1px;
            top: 1px;
            width: 36px;
            text-align: center;
            background: #f7f7f7;
            font-size: 12px;
            color: #919191;
            border-radius: 4px 0 0 4px;
            border-right: 1px solid #d9d9d9;
            font-weight: bold;
            color: #555555;
        }
    }

    table {
        width: 100%;
        border-collapse: collapse;

        thead {
            color: #000000;
            white-space: nowrap;

            th {
                padding: 15px 20px;
                background: #eeeeee;
                text-align: center;
                border: 1px solid #d8d8d8;
                box-sizing: border-box;
                font-size: 14px;
                font-weight: bold;
                color: #000000;

                .popper {
                    margin-left: 2px;
                }

                &>span {
                    display: inline-block;
                    vertical-align: middle;
                    font-size: 14px;
                    font-weight: bold;
                    color: #000000;
                    line-height: 16px;
                }

                &.table-size {
                    width: 104px;
                }

                &.table-product {
                    &>span {
                        line-height: 18px;
                        vertical-align: middle;
                    }

                    .level-discount {
                        display: inline-block;
                        vertical-align: middle;
                        height: 18px;
                        margin: 0;
                        position: relative;

                        &[level='1'] {
                            display: none !important;
                        }
                    }

                    .tooltip+.level-discount {
                        display: block;
                        margin-top: 4px;
                    }
                }

                &.table-brand {
                    .level-discount {
                        display: block;
                        margin-top: 4px;

                        &::v-deep span[name='icon'] {
                            width: 18px;
                            height: 18px;
                            background-size: 18px 18px;
                        }

                        &[level='1'] {
                            display: none;
                        }

                    }
                }

                &.table-retail,
                &.table-profit,
                &.table-margin {
                    &>.pricing-number {
                        display: block;
                    }
                }

                // &.table-cost {
                // }

                // &:nth-child(2),
                // &:nth-child(3) {
                //     width: 16%;
                // }
                // &:nth-child(4),
                // &:nth-child(5),
                // &:nth-child(6) {
                //     width: 19%;
                // }
                .pricing-number {
                    width: 132px;
                    margin: 6px auto 0;
                }

                &:last-child .pricing-number {
                    &::v-deep input {
                        padding-left: 6px;
                        padding-right: 43px;
                    }

                    &::v-deep em {
                        left: auto;
                        right: 1px;
                        border-radius: 0 5px 5px 0;
                        border-left: 1px solid #d9d9d9;
                        border-right: none;
                    }
                }
            }
        }

        tbody {
            td {
                padding: 10px 20px;
                height: 28px;
                line-height: 28px;
                border: 1px solid #d8d8d8;
                white-space: nowrap;
                font-size: 14px;
                color: #000000;
                text-align: center;

                &:last-child .pricing-number {
                    &::v-deep input {
                        padding-left: 6px;
                        padding-right: 43px;
                    }

                    &::v-deep em {
                        left: auto;
                        right: 1px;
                        border-radius: 0 5px 5px 0;
                        border-left: 1px solid #d9d9d9;
                        border-right: none;
                    }
                }

                .level-discount {
                    font-size: 14px;
                }
            }

            tr {
                &:nth-child(2n) {
                    background: #fafafa;
                }

                &.pricing-size {
                    cursor: pointer;

                    td:first-child {
                        position: relative;
                        text-align: center;
                        cursor: pointer;
                        user-select: none;
                        padding-left: 30px;

                        i {
                            position: absolute;
                            width: 14px;
                            height: 14px;
                            line-height: 15px;
                            text-align: center;
                            left: 14px;
                            top: 50%;
                            margin-top: -7px;
                            transform: rotate(0deg);
                            transition: all ease 0.2s;
                            font-size: 12px;
                        }
                    }

                    .pricing-number {
                        &::v-deep input {
                            padding-left: 43px;

                            &:focus~em {
                                border-color: #ea4c89;
                            }
                        }
                    }

                    td:nth-child(2) {
                        text-align: center;
                    }

                    &[open] td:first-child i {
                        transform: rotate(180deg);
                    }

                    td:last-child .pricing-number::v-deep input {
                        padding-left: 6px;
                        padding-right: 43px;
                    }
                }

                &.pricing-child {
                    background: rgba(236, 245, 253, 0.3);
                    display: none;

                    .pricing-number {
                        &::v-deep em {
                            display: none;
                        }

                        &::v-deep input {
                            margin-left: 37px;
                            padding-left: 6px;
                        }
                    }

                    &[open] {
                        display: table-row;
                    }

                    .table-color {
                        text-align: left;
                        position: relative;

                        span {
                            position: relative;
                            left: 50%;
                            margin-left: -35px;
                            display: flex;
                            max-width: 100%;
                            align-items: center;
                        }

                        i {
                            display: inline-block;
                            vertical-align: top;
                            width: 16px;
                            height: 16px;
                            min-width: 16px;
                            box-sizing: border-box;
                            border-radius: 1px;
                            border: 1px solid rgba(0, 0, 0, 0.2);
                            margin-right: 6px;
                        }

                        em {
                            font-size: 12px;
                            white-space: normal;
                            word-break: break-word;
                            line-height: 16px;
                            color: #555;
                        }
                    }

                    td:last-child .pricing-number::v-deep input {
                        margin-left: auto;
                        margin-right: 37px;
                        padding-left: 6px;
                        padding-right: 6px;
                    }
                }

                &:hover {
                    background: rgba(73, 157, 242, 0.1);
                }
            }
        }

        .table-cost,
        .table-brand {
            display: none;
        }

        &.pricing-simply {
            .pricing-number {
                width: 160px;
            }

            .table-profit,
            .table-margin {
                display: none;
            }
        }

        &.pricing-table-branding {

            .table-cost,
            .table-brand {
                display: table-cell;
            }
        }
    }

    .pricing-notify {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.12);
        display: flex;
        align-items: center;
        justify-content: center;

        cite {
            display: flex;
            background: #ffffff;
            box-shadow: 0px 10px 20px 0px rgba(0, 0, 0, 0.18);
            border-radius: 6px;
            padding: 28px;
            align-items: center;

            img {
                width: 24px;
                height: 24px;
            }

            p {
                margin-left: 6px;
                margin-right: 16px;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #f44336;
                line-height: 18px;
                width: 580px;
            }

            button {
                height: 32px;
                width: 68px;
                font-size: 14px;
                border-radius: 4px;
                font-family: Roboto-Medium, Roboto;
                font-weight: 500;

                &+button {
                    margin-left: 8px;
                }
            }
        }
    }
}
</style>
